<template>
  <div class="supplier-container">
    <!-- 页面头部 -->
<!--    <div class="page-header">-->
<!--      <div class="header-left">-->
<!--        <h2 class="page-title">供应商管理</h2>-->
<!--      </div>-->
<!--      <div class="header-right">-->
<!--        <el-button -->
<!--          type="primary" -->
<!--          icon="el-icon-plus" -->
<!--          @click="handleAdd"-->
<!--          class="add-btn"-->
<!--        >-->
<!--          新增供应商-->
<!--        </el-button>-->
<!--      </div>-->
<!--    </div>-->

    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-form">
        <el-input
          v-model="searchKeyword"
          placeholder="请输入供应商名称/联系人"
          class="search-input"
          clearable
          @keyup.enter.native="handleSearch"
        >
          <el-button 
            slot="append" 
            icon="el-icon-search" 
            @click="handleSearch"
            class="search-btn"
          ></el-button>
        </el-input>
        <el-button
          type="primary"
          icon="el-icon-refresh"
          @click="handleReset"
          class="reset-btn"
        >
          重置
        </el-button>

        <div class="header-right" style="margin-left: 500px">
          <el-button
              type="primary"
              icon="el-icon-plus"
              @click="handleAdd"
              class="add-btn"
          >
            新增供应商
          </el-button>
        </div>
      </div>

    </div>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="supplierList"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        class="supplier-table"
      >
        <el-table-column
          prop="index"
          label="序号"
          width="80"
          align="center"
        >
          <template slot-scope="scope">
            {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
          </template>
        </el-table-column>
        
        <el-table-column
          prop="supplierName"
          label="供应商名称"
          min-width="150"
          show-overflow-tooltip
        />
        
        <el-table-column
          prop="contactName"
          label="联系人"
          width="120"
          align="center"
        />
        
        <el-table-column
          prop="contactPhone"
          label="联系电话"
          width="140"
          align="center"
        />
        
        <el-table-column
          prop="email"
          label="邮箱"
          min-width="180"
          show-overflow-tooltip
        />
        
        <el-table-column
          prop="address"
          label="地址"
          min-width="200"
          show-overflow-tooltip
        />
        
        <el-table-column
          label="操作"
          width="150"
          align="center"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="handleEdit(scope.row)"
              class="action-btn edit-btn"
            >
              修改
            </el-button>
            <el-button
              type="text"
              size="small"
              @click="handleDelete(scope.row)"
              class="action-btn delete-btn"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 分页区域 -->
    <div class="pagination-section">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        class="pagination"
      />
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="600px"
      :close-on-click-modal="false"
      class="supplier-dialog"
    >
      <supplier-form
        ref="supplierForm"
        :form-data="formData"
        :is-edit="isEdit"
        @submit="handleSubmit"
        @cancel="handleCancel"
      />
    </el-dialog>
  </div>
</template>

<script>
import { supplierApi } from '@/api/supplier'
import SupplierForm from '@/components/SupplierForm.vue'

export default {
  name: 'SupplierList',
  components: {
    SupplierForm
  },
  data() {
    return {
      // 搜索关键词
      searchKeyword: '',
      
      // 表格数据
      supplierList: [],
      loading: false,
      
      // 分页数据
      currentPage: 1,
      pageSize: 10,
      total: 0,
      
      // 对话框相关
      dialogVisible: false,
      dialogTitle: '新增供应商',
      isEdit: false,
      formData: {}
    }
  },
  created() {
    this.getSupplierList()
  },
  methods: {
    // 获取供应商列表
    async getSupplierList() {
      console.log('开始获取供应商列表...')
      this.loading = true
      try {
        const params = {
          pageNum: this.currentPage,
          pageSize: this.pageSize
        }
        // 只有当搜索关键词不为空时才添加
        if (this.searchKeyword && this.searchKeyword.trim()) {
          params.supplierName = this.searchKeyword.trim()
        }
        console.log('请求参数:', params)
        
        // 如果有搜索关键词，使用搜索接口
        if (this.searchKeyword && this.searchKeyword.trim()) {
          console.log('使用搜索接口，关键词:', this.searchKeyword)
          const response = await supplierApi.searchSuppliers(this.searchKeyword)
          console.log('搜索结果:', response)
          this.supplierList = response.data || []
          this.total = this.supplierList.length
        } else {
          console.log('使用分页接口')
          const response = await supplierApi.getSupplierListByPage(params)
          console.log('分页接口响应:', response)
          
          // 根据后端返回的数据结构处理
          if (response.data && response.data.records) {
            console.log('使用 PageResult 格式数据')
            this.supplierList = response.data.records || []
            this.total = response.data.total || 0
          } else if (Array.isArray(response.data)) {
            console.log('使用数组格式数据')
            this.supplierList = response.data
            this.total = response.data.length
          } else {
            console.log('数据格式不匹配，使用空数组')
            this.supplierList = []
            this.total = 0
          }
        }
        console.log('最终数据:', this.supplierList)
        console.log('总数:', this.total)
      } catch (error) {
        console.error('获取供应商列表失败:', error)
        this.$message.error('获取供应商列表失败: ' + (error.message || '未知错误'))
        this.supplierList = []
        this.total = 0
      } finally {
        this.loading = false
        console.log('加载完成，loading状态:', this.loading)
      }
    },

    // 搜索
    handleSearch() {
      this.currentPage = 1
      this.getSupplierList()
    },

    // 重置搜索
    handleReset() {
      this.searchKeyword = ''
      this.currentPage = 1
      this.getSupplierList()
    },

    // 新增供应商
    handleAdd() {
      this.dialogTitle = '新增供应商'
      this.isEdit = false
      this.formData = {}
      this.dialogVisible = true
    },

    // 编辑供应商
    async handleEdit(row) {
      this.dialogTitle = '编辑供应商'
      this.isEdit = true
      this.formData = { ...row }
      this.dialogVisible = true
      console.log('编辑供应商:', row)
    },

    // 删除供应商
    handleDelete(row) {
      this.$confirm('确定要删除该供应商吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        try {
          await supplierApi.deleteSupplier(row.supplierId)
          this.$message.success('删除成功')
          this.getSupplierList()
        } catch (error) {
          console.error('删除供应商失败:', error)
          this.$message.error('删除失败: ' + (error.message || '未知错误'))
        }
      }).catch(() => {
        this.$message.info('已取消删除')
      })
    },

    // 提交表单
    async handleSubmit(formData) {
      try {
        console.log('提交的表单数据:', formData)
        console.log('是否包含supplierId:', 'supplierId' in formData)
        console.log('supplierId值:', formData.supplierId)
        
        if (this.isEdit) {
          await supplierApi.updateSupplier(formData)
          this.$message.success('更新成功')
        } else {
          await supplierApi.addSupplier(formData)
          this.$message.success('新增成功')
        }
        this.dialogVisible = false
        this.getSupplierList()
      } catch (error) {
        console.error('提交表单失败:', error)
        this.$message.error('操作失败: ' + (error.message || '未知错误'))
      }
    },

    // 取消表单
    handleCancel() {
      this.dialogVisible = false
    },

    // 分页大小改变
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getSupplierList()
    },

    // 当前页改变
    handleCurrentChange(val) {
      this.currentPage = val
      this.getSupplierList()
    }
  }
}
</script>

<style scoped>
.supplier-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

/* 页面头部样式 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.page-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin: 0;
}

.add-btn {
  padding: 12px 24px;
  font-size: 14px;
  border-radius: 6px;
}

/* 搜索区域样式 */
.search-section {
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-form {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  width: 300px;
}

.search-input .el-input__inner {
  border-radius: 6px;
}

.search-btn {
  background-color: #409eff;
  border-color: #409eff;
}

.reset-btn {
  padding: 10px 20px;
  border-radius: 6px;
}

/* 表格区域样式 */
.table-section {
  margin-bottom: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.supplier-table {
  border-radius: 8px;
}

.supplier-table .el-table__header {
  background-color: #fafafa;
}

.supplier-table .el-table__header th {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

.action-btn {
  padding: 4px 8px;
  margin: 0 4px;
  border-radius: 4px;
  transition: all 0.3s;
}

.edit-btn {
  color: #409eff;
}

.edit-btn:hover {
  background-color: #ecf5ff;
  color: #66b1ff;
}

.delete-btn {
  color: #f56c6c;
}

.delete-btn:hover {
  background-color: #fef0f0;
  color: #f78989;
}

/* 分页区域样式 */
.pagination-section {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  text-align: center;
}

/* 对话框样式 */
.supplier-dialog .el-dialog__header {
  background-color: #f8f9fa;
  border-bottom: 1px solid #e9ecef;
  border-radius: 8px 8px 0 0;
}

.supplier-dialog .el-dialog__title {
  font-weight: 600;
  color: #303133;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .supplier-container {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 15px;
    align-items: stretch;
  }
  
  .search-form {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    width: 100%;
  }
  
  .supplier-table {
    font-size: 12px;
  }
}
</style>
